<?php

class Application_Model_Dao_CustomerMapper extends Base_Mapper
{
	
	function __construct() {
		parent::__construct();
		$this->tableName = 'Application_Model_DbTable_Customer';
	}
	
	
   
	public function save(Application_Model_BusiInfo_Customer $customer)
	{
		$data = array(
			'name'   => $customer->get_name(),
			'tax_id' => $customer->get_taxId(),
			'address' => $customer->get_address(),
			'phone' => $customer->get_phone(),
			'bank' => $customer->get_bank(),
			'account' => $customer->get_account(),
		);

		$id = $customer->get_id();
		if ($id === null || $id === "") {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
   
	public function find($id)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$this->logger->debug(print_r($row, true));
		return new Application_Model_BusiInfo_Customer($row->toArray());		
	}
   
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {	
			$entry = $this->toModel($row);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	private function toModel($record){
		$customer = new Application_Model_BusiInfo_Customer(); 
		$customer->set_id($record->id);
	    $customer->set_name($record->name);
	    $customer->set_taxId($record->tax_id);
	    $customer->set_address($record->address);
	    $customer->set_phone($record->phone);
	    $customer->set_bank($record->bank);
	    $customer->set_account($record->account); 
	    return $customer;
		
	}
	
	public function delete($customerId) {
		$where = 'id = ' .  $customerId;
		$this->getDbTable()->delete($where);
	}
}

